<template>
  <div class="character-detail-container">
    <div class="container">
      <!-- 导航返回按钮 -->
      <div class="navigation">
        <button @click="goBack" class="back-button">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M19 12H5M12 19l-7-7 7-7"></path>
          </svg>
          返回
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="characterStore.loading && !characterStore.character" class="loading">
        加载角色信息中...
      </div>

      <!-- 错误状态 -->
      <div v-else-if="characterStore.error" class="error-message">
        {{ characterStore.error }}
        <button @click="retryLoading" class="retry-btn">重试</button>
      </div>

      <!-- 角色详情内容 -->
      <div v-else-if="characterStore.character" class="character-detail">
        <!-- 角色头部信息 -->
        <div class="character-header">
          <div class="character-avatar-large">
            <img :src="characterStore.character.avatar" :alt="characterStore.character.name" />
          </div>
          <div class="character-info">
            <h1>{{ characterStore.character.name }}</h1>
            <div class="character-categories">
              <span v-for="category in characterStore.character.categories" :key="category" class="category-tag">
                {{ category }}
              </span>
            </div>
            <div class="character-stats">
              <div class="stat-item">
                <span class="stat-label">创建时间</span>
                <span class="stat-value">{{ formatDate(characterStore.character.createdAt) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">最后更新</span>
                <span class="stat-value">{{ formatDate(characterStore.character.updatedAt) }}</span>
              </div>
            </div>
            <div class="action-buttons">
              <router-link
                :to="{ name: 'chat', params: { characterId: characterStore.character.id } }"
                class="btn-primary start-chat-btn"
                v-if="authStore.isAuthenticated"
              >
                开始对话
              </router-link>
              <button @click="goToLogin" class="btn-secondary login-prompt-btn" v-else>
                登录开始对话
              </button>
              <button @click="shareCharacter" class="btn-share">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
                  <polyline points="15 3 21 3 21 9"></polyline>
                  <line x1="10" y1="14" x2="21" y2="3"></line>
                </svg>
                分享
              </button>
            </div>
          </div>
        </div>

        <!-- 角色描述和个性特点 -->
        <div class="character-details-content">
          <div class="detail-section">
            <h2>角色介绍</h2>
            <p class="description-text">{{ characterStore.character.description }}</p>
          </div>

          <div class="detail-section">
            <h2>个性特点</h2>
            <p class="personality-text">{{ characterStore.character.personality }}</p>
          </div>

          <!-- 对话提示建议 -->
          <div class="detail-section conversation-tips">
            <h2>对话提示建议</h2>
            <div class="tips-grid">
              <button
                v-for="(tip, index) in conversationTips"
                :key="index"
                @click="useConversationTip(tip)"
                class="tip-card"
              >
                {{ tip }}
              </button>
            </div>
          </div>

          <!-- 相关角色 -->
          <div class="detail-section related-characters" v-if="relatedCharacters.length > 0">
            <h2>相关角色</h2>
            <div class="related-characters-grid">
              <div v-for="related in relatedCharacters" :key="related.id" class="related-character-card">
                <img :src="related.avatar" :alt="related.name" class="related-character-avatar" />
                <div class="related-character-info">
                  <h3>{{ related.name }}</h3>
                  <p class="related-character-description">{{ related.description.substring(0, 60) }}...</p>
                  <router-link :to="{ name: 'character-detail', params: { id: related.id } }" class="view-more-link">
                    查看详情
                  </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 管理员操作区 -->
        <div v-if="authStore.isAuthenticated && authStore.user?.role === 'admin'" class="admin-actions">
          <h3>管理员操作</h3>
          <div class="admin-actions-buttons">
            <button @click="editCharacter" class="btn-edit">编辑角色</button>
            <button @click="deleteCharacterConfirm" class="btn-delete">删除角色</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { characterStore } from '../store/character';
import { authStore } from '../store/auth';

const router = useRouter();
const route = useRoute();
const characterStoreRef = characterStore();
const authStoreRef = authStore();

// 对话提示建议
const conversationTips = ref([
  '你好，能介绍一下你自己吗？',
  '你最擅长的领域是什么？',
  '你能给我一些关于学习的建议吗？',
  '你对当前热门话题有什么看法？',
  '你有什么兴趣爱好？'
]);

// 相关角色（模拟数据，实际应该从API获取）
const relatedCharacters = ref([]);

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  }).format(date);
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 重试加载
const retryLoading = () => {
  characterStoreRef.clearError();
  loadCharacterDetail();
};

// 跳转到登录页
const goToLogin = () => {
  router.push({ name: 'login' });
};

// 分享角色
const shareCharacter = () => {
  if (navigator.share) {
    navigator.share({
      title: characterStoreRef.character.name,
      text: characterStoreRef.character.description,
      url: window.location.href
    }).catch((error) => {
      console.error('分享失败:', error);
      alert('分享失败，请手动复制链接分享。');
    });
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      alert('链接已复制到剪贴板！');
    }).catch(() => {
      alert('复制失败，请手动复制浏览器地址栏的链接。');
    });
  }
};

// 使用对话提示
const useConversationTip = (tip) => {
  // 跳转到聊天页面并带上提示文本
  router.push({
    name: 'chat',
    params: { characterId: characterStoreRef.character.id },
    query: { initialMessage: tip }
  });
};

// 编辑角色（管理员功能）
const editCharacter = () => {
  // 这里应该跳转到编辑页面或显示编辑表单
  alert('编辑角色功能待实现');
};

// 删除角色确认（管理员功能）
const deleteCharacterConfirm = () => {
  if (confirm(`确定要删除角色 "${characterStoreRef.character.name}" 吗？此操作不可撤销。`)) {
    deleteCharacter();
  }
};

// 删除角色（管理员功能）
const deleteCharacter = async () => {
  try {
    await characterStoreRef.deleteCharacter(characterStoreRef.character.id);
    alert('角色已成功删除');
    router.push({ name: 'home' });
  } catch (error) {
    console.error('删除角色失败:', error);
  }
};

// 加载角色详情
const loadCharacterDetail = async () => {
  const characterId = route.params.id;
  try {
    await characterStoreRef.getCharacterById(characterId);
    // 这里可以加载相关角色的数据
    loadRelatedCharacters();
  } catch (error) {
    console.error('加载角色详情失败:', error);
  }
};

// 加载相关角色（模拟实现）
const loadRelatedCharacters = () => {
  // 这里应该从API获取相关角色，现在使用模拟数据
  // 从所有角色中筛选出与当前角色有共同分类的角色
  const currentCharacter = characterStoreRef.character;
  if (!currentCharacter) return;
  
  // 模拟数据，实际应该从API获取
  const allCharacters = [
    {
      id: 3,
      name: '牛顿',
      description: '英国物理学家、数学家，万有引力定律发现者',
      avatar: 'https://example.com/avatars/newton.png',
      categories: ['科学家', '历史人物']
    },
    {
      id: 4,
      name: '居里夫人',
      description: '物理学家、化学家，首位获得两次诺贝尔奖的人',
      avatar: 'https://example.com/avatars/curie.png',
      categories: ['科学家', '历史人物']
    }
  ];
  
  // 过滤出有共同分类且不是当前角色的角色
  relatedCharacters.value = allCharacters.filter(character => 
    character.id !== currentCharacter.id &&
    character.categories.some(category => currentCharacter.categories.includes(category))
  );
};

// 组件挂载时
onMounted(() => {
  // 加载用户认证状态
  authStoreRef.loadFromStorage();
  // 加载角色详情
  loadCharacterDetail();
});
</script>

<style scoped>
/* 全局样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 导航样式 */
.navigation {
  margin: 20px 0;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
  color: #333;
}

.back-button:hover {
  background-color: #f8f9fa;
  border-color: #667eea;
  color: #667eea;
}

/* 加载和错误状态 */
.loading {
  text-align: center;
  padding: 60px 20px;
  color: #666;
  font-size: 1.1rem;
}

.error-message {
  background-color: #fed7d7;
  color: #c53030;
  padding: 15px 20px;
  border-radius: 5px;
  margin: 20px 0;
  text-align: center;
}

.retry-btn {
  margin-left: 10px;
  padding: 5px 15px;
  background-color: #c53030;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.9rem;
}

/* 角色详情内容 */
.character-detail-container {
  padding: 20px 0;
  min-height: 100vh;
  background-color: #f8f9fa;
}

.character-detail {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 角色头部信息 */
.character-header {
  display: flex;
  gap: 30px;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  flex-wrap: wrap;
}

.character-avatar-large {
  flex: 0 0 200px;
  height: 200px;
  border-radius: 50%;
  overflow: hidden;
  border: 5px solid rgba(255, 255, 255, 0.3);
  flex-shrink: 0;
}

.character-avatar-large img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.character-info {
  flex: 1;
  min-width: 300px;
}

.character-info h1 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 2.5rem;
}

.character-categories {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.category-tag {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 0.9rem;
}

.character-stats {
  display: flex;
  gap: 30px;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
}

.stat-label {
  font-size: 0.85rem;
  opacity: 0.8;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 1rem;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

/* 角色详细内容 */
.character-details-content {
  padding: 40px;
}

.detail-section {
  margin-bottom: 40px;
}

.detail-section h2 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 1.75rem;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 2px solid #e0e0e0;
}

.description-text,
.personality-text {
  font-size: 1.1rem;
  line-height: 1.8;
  color: #666;
  margin: 0;
}

/* 对话提示建议 */
.conversation-tips {
  background-color: #f8f9fa;
  padding: 30px;
  border-radius: 10px;
}

.tips-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 15px;
}

.tip-card {
  padding: 15px 20px;
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
  text-align: left;
  color: #333;
  line-height: 1.5;
}

.tip-card:hover {
  background-color: #667eea;
  color: white;
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

/* 相关角色 */
.related-characters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.related-character-card {
  display: flex;
  gap: 15px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  transition: all 0.3s ease;
}

.related-character-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.related-character-avatar {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  object-fit: cover;
  flex-shrink: 0;
}

.related-character-info {
  flex: 1;
  min-width: 0;
}

.related-character-info h3 {
  margin-top: 0;
  margin-bottom: 5px;
  font-size: 1.2rem;
  color: #333;
}

.related-character-description {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 0.95rem;
  color: #666;
  line-height: 1.5;
}

.view-more-link {
  color: #667eea;
  text-decoration: none;
  font-size: 0.9rem;
  font-weight: 600;
}

.view-more-link:hover {
  text-decoration: underline;
}

/* 管理员操作 */
.admin-actions {
  padding: 20px 40px;
  background-color: #f8f9fa;
  border-top: 1px solid #e0e0e0;
}

.admin-actions h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.admin-actions-buttons {
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.btn-primary,
.btn-secondary,
.btn-share,
.btn-edit,
.btn-delete {
  padding: 12px 24px;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-primary {
  background-color: rgba(255, 255, 255, 0.9);
  color: #667eea;
}

.btn-primary:hover {
  background-color: white;
}

.btn-secondary {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.btn-secondary:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.btn-share {
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.btn-share:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.btn-edit {
  background-color: #3182ce;
  color: white;
}

.btn-edit:hover {
  background-color: #2c5aa0;
}

.btn-delete {
  background-color: #e53e3e;
  color: white;
}

.btn-delete:hover {
  background-color: #c53030;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .character-header {
    flex-direction: column;
    text-align: center;
    padding: 30px 20px;
  }
  
  .character-avatar-large {
    margin: 0 auto;
  }
  
  .character-info h1 {
    font-size: 2rem;
  }
  
  .character-stats {
    justify-content: center;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .character-details-content {
    padding: 20px;
  }
  
  .detail-section {
    margin-bottom: 30px;
  }
  
  .tips-grid {
    grid-template-columns: 1fr;
  }
  
  .related-characters-grid {
    grid-template-columns: 1fr;
  }
  
  .admin-actions {
    padding: 20px;
  }
  
  .admin-actions-buttons {
    flex-direction: column;
  }
  
  .btn-primary,
  .btn-secondary,
  .btn-share {
    width: 100%;
    justify-content: center;
  }
}
</style>